import React, { useState, useEffect } from 'react';
import { Table, Drawer, Space, Button, Popconfirm, Input, Select, Tree, Modal, notification } from 'antd';
import { getAdminList, addAdmin, updateAdmin, deleteAdmin } from '../../api/user';
import menus from './../../router/menus';

function Index() {
  // 1.管理员列表
  const [adminList, setAdminList] = useState([]);
  useEffect(() => {
    getAdminList().then((res) => {
      setAdminList(res.data.data);
    });
  }, []);
  const columns = [
    {
      title: '序号',
      render: (text, record, index) => <span>{index + 1}</span>
    },
    {
      title: '账户',
      dataIndex: 'adminname'
    },
    {
      title: '权限',
      dataIndex: 'role',
      render: (text) => {
        return text === 2 ? '超级管理员' : '管理员';
      }
    },
    {
      title: '操作',
      render: (text, record, index) => {
        return (
          <Space>
            {/* 3.编辑管理员数据 */}
            <Button
              type='dashed'
              onClick={() => {
                setIsModalVisible(true);
                // 3.修改表单的数据状态
                setUadminname(record.adminname);
                setUrole(record.role + '');
                setUcheckedKeys(record.checkedKeys);
              }}>
              编辑
            </Button>
            <Popconfirm
              title='确定删除吗?'
              onConfirm={() => {
                deleteAdmin({ adminid: record.adminid }).then(() => {
                  getAdminList().then((res) => setAdminList(res.data.data));
                });
              }}
              okText='确定'
              cancelText='取消'>
              <Button type='danger'>删除</Button>
            </Popconfirm>
          </Space>
        );
      }
    }
  ];
  // 2.添加管理员 - 控制抽屉的显示
  const [visible, setVisible] = useState(false);
  const showDrawer = () => {
    setVisible(true);
  };
  // 2.添加管理员 - 需要的组件状态
  const [adminname, setAdminname] = useState('');
  const [password, setPasssword] = useState('');
  const [role, setRole] = useState('1');
  const [checkedKeys, setCheckedKeys] = useState([]); // 用来记录哪些被选中
  const changeRole = (value) => {
    setRole(value);
  };
  const onCheck = (checkedKeys) => {
    console.log(checkedKeys);
    setCheckedKeys(checkedKeys);
  };
  const addAdminFn = () => {
    const obj = { adminname, password, role, checkedKeys };
    console.log(obj);
    addAdmin(obj).then((res) => {
      if (res.data.code === '10004') {
        notification.warning({
          duration: 2,
          message: '消息提醒',
          description: '该管理员已存在',
          onClick: () => {}
        });
      } else {
        // 抽屉消失，表单回归初始状态
        setVisible(false);
        setAdminname('');
        setPasssword('');
        setRole('1');
        setCheckedKeys([]);
        // 重新渲染一次页面
        getAdminList().then((res) => {
          setAdminList(res.data.data);
        });
      }
    });
  };
  // const expandedKeys = ['0-2']
  const expandedKeys = [];
  menus.forEach((item) => {
    expandedKeys.push(item.key);
  });

  // 3.编辑管理员数据 - 控制对话框的展示
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 3.编辑管理员数据 - 输入框的值
  const [uadminname, setUadminname] = useState('');
  const [urole, setUrole] = useState('1');
  const [ucheckedKeys, setUcheckedKeys] = useState([]);
  const changeURole = (value) => {
    setUrole(value);
  };
  const onUCheck = (checkedKeys) => {
    console.log(checkedKeys);
    setUcheckedKeys(checkedKeys);
  };
  return (
    <div>
      {/* 2.添加管理员 */}
      <Button type='primary' onClick={showDrawer}>
        添加管理员
      </Button>
      <Drawer
        width={500}
        title='添加管理员'
        placement='right'
        closable={true}
        onClose={() => {
          setVisible(false);
        }}
        visible={visible}>
        <Space direction='vertical'>
          <Input
            placeholder='请输入账户名'
            value={adminname}
            onChange={(e) => {
              setAdminname(e.target.value);
            }}
          />
          <Input
            type='password'
            placeholder='请输入密码'
            value={password}
            onChange={(e) => {
              setPasssword(e.target.value);
            }}
          />
          <Select value={role} onChange={changeRole}>
            <Select.Option value='2'>超级管理员</Select.Option>
            <Select.Option value='1'>管理员</Select.Option>
          </Select>
          <Tree
            checkable // 前面添加复选框
            expandedKeys={expandedKeys} // 自动展开哪些二级菜单
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            treeData={menus}
          />
          <Button type='primary' onClick={addAdminFn}>
            添加
          </Button>
        </Space>
      </Drawer>
      {/* 1.管理员列表 */}
      <Table rowKey={(record) => record.adminid} dataSource={adminList} columns={columns} />
      {/* 3.编辑管理员数据 */}
      <Modal
        title='更新管理员信息'
        visible={isModalVisible}
        onOk={() => {
          const obj = { adminname: uadminname, role: urole, checkedKeys: ucheckedKeys };
          console.log('更新数据', obj);

          updateAdmin(obj).then(() => {
            setIsModalVisible(false);
            getAdminList().then((res) => setAdminList(res.data.data));
          });
        }}
        onCancel={() => {
          setIsModalVisible(false);
        }}>
        <Space direction='vertical'>
          <Input placeholder='请输入账户名' value={uadminname} readOnly />
          <Select value={urole} onChange={changeURole}>
            <Select.Option value='2'>超级管理员</Select.Option>
            <Select.Option value='1'>管理员</Select.Option>
          </Select>
          <Tree
            checkable // 前面添加复选框
            expandedKeys={expandedKeys} // 自动展开哪些二级菜单
            onCheck={onUCheck}
            checkedKeys={ucheckedKeys}
            treeData={menus}
          />
        </Space>
      </Modal>
    </div>
  );
}

export default Index;
